/*
 * @Author: lichao 1246877006@qq.com
 * @Date: 2024-09-25 14:44:40
 * @LastEditors: lichao 1246877006@qq.com
 * @LastEditTime: 2024-09-25 15:06:53
 * @FilePath: \algorithm\hello-algo\4 数组与链表\4.2 链表.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 节点类
class ListNode {
    constructor(val, next) {
        this.val = (val === undefined ? 0 : val)
        this.next = (next === undefined ? null : next)
    }
}

// 初始化链表
const n0 = new ListNode(1)
const n1 = new ListNode(2)
const n2 = new ListNode(3)
const n3 = new ListNode(4)
const n4 = new ListNode(5)
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4

// 插入数据
function insert(n0, p) {
    const n1 = n0.next
    p.next = n1
    n0.next = p
}

// 删除节点
function remove(n0) {
    if(!n0.next) return
    const p = n0.next
    const n1 = p.next
    n0.next = n1
}

// 访问节点
function access(head, index) {
    for(let i = 0; i < index; i++) {
        if(!head) return null
        head = head.next
    }
    return head
}

// 查找结点
function find(head, target) {
    let index = 0
    while(head !== null) {
        if(head.val === target) {
            return index
        }
        head = head.next
        index++
    }
    return -1
}